package com.frame.common.core.security.config;

import com.frame.common.core.security.entity.SecurityUser;
import com.frame.common.core.security.utils.SecurityUtils;
import com.frame.common.core.security.utils.TokenUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.authentication.www.BasicAuthenticationFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Slf4j
public class UserAuthFilter extends BasicAuthenticationFilter {

    private TokenUtil tokenUtil;

    public UserAuthFilter(TokenUtil tokenUtil, AuthenticationManager authenticationManager) {
        super(authenticationManager);
        this.tokenUtil = tokenUtil;
    }

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain) throws IOException, ServletException {
        SecurityUser currentUser = tokenUtil.getCurrentUser(request);
        if(Objects.nonNull(currentUser)){
            tokenUtil.verifyToken(currentUser);

            if(Objects.isNull(SecurityUtils.getAuthentication())){
                UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(currentUser, null, currentUser.getAuthorities());
                authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                log.info("authenticated user " + currentUser.getUsername() + ", setting security context");
                SecurityContextHolder.getContext().setAuthentication(authenticationToken);
            }
        }
        chain.doFilter(request, response);
    }

}
